package com.purong.purong.activity;

import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.purong.purong.Contant;
import com.purong.purong.R;
import com.purong.purong.adapter.BankLoanAdapter;
import com.purong.purong.bean.CreditSearchBean;
import com.purong.purong.bean.CreditSearchBean.SearchType;
import com.purong.purong.bean.CreditSearchBean.SearchType.SearchItem;
import com.purong.purong.bean.BankLoanBean;
import com.purong.purong.bean.BankLoanSearchListBean;
import com.purong.purong.bean.SearchValueBean;
import com.purong.purong.util.SharePreUtil;
import com.purong.purong.widget.SearchNormalDialog;
import com.purong.purong.widget.SearchMoreDialog;
import com.purong.purong.widget.LoadingView;
import com.yao.sdk.net.ResponseInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrCustomHandler;
import in.srain.cube.views.ptr.PtrDefaultCustomHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrPuRongLayout;

/**
 * Created by wenjiezeng on 2017/9/25.
 */
public class LoanSearchActivity extends BaseActivity {
    private SearchNormalDialog pledgeSearchDialog, orderSearchDialog;
    private SearchMoreDialog moreSearchDialog;
    private SearchValueBean chosePledge, choseOrder;
    private List<SearchValueBean> choseMoreList = new ArrayList<>();
    private ArrayList<SearchValueBean> mPledgeList;
    private ArrayList<SearchValueBean> mOrderList;
    private ArrayList<SearchItem> mMoreList;
    private CreditSearchBean searchBean;
    private TextView pledgeTv, orderTv, moreTv;
    private ImageView pledgeImg, orderImg, moreImg;

    private ListView mListView;
    private BankLoanAdapter mAdapter;
    private List<BankLoanBean> loanList = new ArrayList<>();
    private PtrPuRongLayout mPtrFrame;
    private LoadingView loadView;
    private int page = 1;

    //    private SearchValueBean choseUse,choseLevel;
    private Map<String, String> itemMap = new HashMap<>();

    @Override
    public int getRootViewId() {
        return R.layout.activity_loan_search;
    }

    public void initView() {
        findViewById(R.id.left_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                LoanSearchActivity.this.finish();
            }
        });
        pledgeTv = (TextView) findViewById(R.id.pledge_tv);
        orderTv = (TextView) findViewById(R.id.order_tv);
        moreTv = (TextView) findViewById(R.id.more_tv);
        pledgeImg = (ImageView) findViewById(R.id.pledge_img);
        orderImg = (ImageView) findViewById(R.id.order_img);
        moreImg = (ImageView) findViewById(R.id.more_img);
        loadView = (LoadingView) findViewById(R.id.loading_view);
        loadView.setNoResultToast("未找到符合条件的产品", "清空筛选");
        loadView.setLoadListener(new LoadingView.OnLoadListener() {
            @Override
            public void onReload() {
                getLoan(true);
            }

            @Override
            public void onRefresh() {
                if (mPledgeList != null) {
                    for (int i = 0; i < mPledgeList.size(); i++) {
                        if (mPledgeList.get(i).getItem().equals("-1")) {
                            mPledgeList.get(i).setCheck(true);
                            chosePledge = mPledgeList.get(i);
                        } else {
                            mPledgeList.get(i).setCheck(false);
                        }
                    }
                }
                if (mOrderList != null) {
                    for (int i = 0; i < mOrderList.size(); i++) {
                        if (mOrderList.get(i).getItem().equals("-1")) {
                            mOrderList.get(i).setCheck(true);
                            choseOrder = mOrderList.get(i);
                        } else {
                            mOrderList.get(i).setCheck(false);
                        }
                    }
                }
                if (mMoreList != null) {
                    for (int i = 0; i < mMoreList.size(); i++) {
                        for (int j = 0; j < mMoreList.get(i).getValue().size(); j++) {
                            mMoreList.get(i).getValue().get(j).setCheck(false);
                        }
                    }
                }

                pledgeTv.setText("不限抵押");
                orderTv.setText("默认排序");
                setStatus(pledgeTv, pledgeImg, 1);
                setStatus(orderTv, orderImg, 1);
                setStatus(moreTv, moreImg, 1);
                getLoan(true);
            }
        });

        mListView = (ListView) findViewById(R.id.list_view);
        mAdapter = new BankLoanAdapter(this, loanList);
        mListView.setAdapter(mAdapter);
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent=new Intent(LoanSearchActivity.this,BankLoanDetialActivity.class);
                intent.putExtra("LOAN",loanList.get(position));
                startActivity(intent);
            }
        });
        mPtrFrame = (PtrPuRongLayout) findViewById(R.id.rotate_header_list_view_frame);
        mPtrFrame.setPtrHandler(new PtrCustomHandler() {
            @Override
            public boolean checkCanDoLoadMore(PtrFrameLayout frame, View content, View footer) {
                if (loanList.size() == 0) {
                    return false;
                } else {
                    return PtrDefaultCustomHandler.checkContentCanBePulledUp(frame, content, footer);
                }

            }

            @Override
            public void onLoadMoreBegin(PtrFrameLayout frame) {
                getLoan(false);

            }

            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                getLoan(true);
            }

            @Override
            public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
                return false;
//                return (isRequesting||loanList.size()>0)?false:true;
            }
        });



    }

    @Override
    public void initBundle() {
        chosePledge = (SearchValueBean) getIntent().getSerializableExtra("CHOSE_PLEDGE");
        choseOrder = (SearchValueBean) getIntent().getSerializableExtra("CHOSE_ORDER");
        choseMoreList = (List<SearchValueBean>) getIntent().getSerializableExtra("CHOSE_MORE");
    }

    @Override
    public void initData() {
        getSearch("2", "1", "1");
    }


    private void setStatus(TextView tv, ImageView iv, int status) {
        //status 1:下黑，2：下蓝，3：上黑，4：上篮
        switch (status) {
            case 1:
                tv.setTextColor(getResources().getColor(R.color.text_gray));
                iv.setImageResource(R.drawable.cart_gray_down);
                break;
            case 2:
                tv.setTextColor(getResources().getColor(R.color.blue));
                iv.setImageResource(R.drawable.cart_blue_down);
                break;
            case 3:
                tv.setTextColor(getResources().getColor(R.color.text_gray));
                iv.setImageResource(R.drawable.cart_black_up);
                break;
            case 4:
                tv.setTextColor(getResources().getColor(R.color.blue));
                iv.setImageResource(R.drawable.cart_blue_top);
                break;
        }
    }

    private void initSearchData() {
        if (searchBean == null || searchBean.getLoan_loan_item_list() == null)
            return;
        List<SearchType> typeList = searchBean.getLoan_loan_item_list();
        for (int i = 0; i < typeList.size(); i++) {
            for (int j = 0; j < typeList.get(i).getSearch_item().size(); j++) {
                for (int k = 0; k < typeList.get(i).getSearch_item().get(j).getValue().size(); k++) {
                    if (chosePledge != null && typeList.get(i).getSearch_item().get(j).getFiled().equals(chosePledge.getParentFiled())
                            && typeList.get(i).getSearch_item().get(j).getValue().get(k).getItem().equals(chosePledge.getItem())) {
                        typeList.get(i).getSearch_item().get(j).getValue().get(k).setCheck(true);
                        chosePledge.setTitle(typeList.get(i).getSearch_item().get(j).getValue().get(k).getTitle());
                        pledgeTv.setText(typeList.get(i).getSearch_item().get(j).getValue().get(k).getTitle());
                        setStatus(pledgeTv, pledgeImg, 2);
                        continue;
                    }
                    if (choseOrder != null && typeList.get(i).getSearch_item().get(j).getFiled().equals(choseOrder.getParentFiled())
                            && typeList.get(i).getSearch_item().get(j).getValue().get(k).getItem().equals(choseOrder.getItem())) {
                        typeList.get(i).getSearch_item().get(j).getValue().get(k).setCheck(true);
                        choseOrder.setTitle(typeList.get(i).getSearch_item().get(j).getValue().get(k).getTitle());
                        orderTv.setText(typeList.get(i).getSearch_item().get(j).getValue().get(k).getTitle());
                        setStatus(orderTv, orderImg, 2);
                        continue;
                    }
                    if (choseMoreList != null) {
                        boolean hasMore = false;
                        for (int n = 0; n < choseMoreList.size(); n++) {
                            if (typeList.get(i).getSearch_item().get(j).getFiled().equals(choseMoreList.get(n).getParentFiled())
                                    && typeList.get(i).getSearch_item().get(j).getValue().get(k).getItem().equals(choseMoreList.get(n).getItem())) {
                                typeList.get(i).getSearch_item().get(j).getValue().get(k).setCheck(true);
                                hasMore = true;
                                break;
                            }
                        }
                        if (hasMore) {
                            setStatus(moreTv, moreImg, 2);
                        }
                    }

                }

            }
        }

    }

    private void getLoan(boolean clear) {
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("province_id", SharePreUtil.getInstance(this).getLoactionParentId());
        params.put("city_id", SharePreUtil.getInstance(this).getLoactionAreaId());
        if (searchBean != null) {
            itemMap.clear();
            List<SearchType> typeList = searchBean.getLoan_loan_item_list();
            for (int i = 0; i < typeList.size(); i++) {
                for (int j = 0; j < typeList.get(i).getSearch_item().size(); j++) {
                    for (int k = 0; k < typeList.get(i).getSearch_item().get(j).getValue().size(); k++) {
                        if (typeList.get(i).getSearch_item().get(j).getValue().get(k).isCheck()) {
                            itemMap.put(typeList.get(i).getSearch_item().get(j).getFiled(), typeList.get(i).getSearch_item().get(j).getValue().get(k).getItem());
                        }
                    }
                }
            }
            for (Map.Entry<String, String> entry : itemMap.entrySet()) {
                params.put(entry.getKey(), entry.getValue());
            }
        }
        if (clear) {
            page = 1;
            loanList.clear();
            mAdapter.notifyDataSetChanged();
            loadView.loading();

        }
//        noResult.setVisibility(View.GONE);
        params.put("page", page + "");

        if (!request(Contant.LOAN_SEARCH_LIST, params, true)) {
            if (clear)
                loadView.fail();
            if (!hasDestroy())
                new Handler().postDelayed(new Runnable() {
                    public void run() {
                        if (mPtrFrame.isRefreshing()) {
                            mPtrFrame.refreshComplete();
                        }
                    }
                }, 100);
        }
    }

    private void getSearch(String firstLoad, String needShow, String type) {
        cancelRequest();
        Map<String, String> params = new LinkedHashMap<String, String>();
        params.put("first_load", firstLoad);
        params.put("need_show", needShow);
        params.put("type", type);
        if (needShow.equals("1")) {
            request(Contant.LOAN_SEARCH, params, true, false);
        } else {
            request(Contant.LOAN_SEARCH, params, true, true);
        }

    }

    private void initPledgeDialog() {
        pledgeSearchDialog = new SearchNormalDialog(this, mPledgeList, true, false, new SearchNormalDialog.OnSearchChoseListener() {
            @Override
            public void onChose(int position) {
                chosePledge = mPledgeList.get(position);
                getLoan(true);
            }

            @Override
            public void onShow() {
                setStatus(pledgeTv, pledgeImg, 4);
            }

            @Override
            public void onDismiss() {
                if (chosePledge != null) {
                    pledgeTv.setText(chosePledge.getTitle());
                    if (chosePledge.getItem().equals("-1")) {
                        setStatus(pledgeTv, pledgeImg, 1);
                    } else {
                        setStatus(pledgeTv, pledgeImg, 2);
                    }

                } else {
                    setStatus(pledgeTv, pledgeImg, 1);
                }

            }
        });
    }

    private void initOrderDialog() {
        orderSearchDialog = new SearchNormalDialog(this, mOrderList, false, false, new SearchNormalDialog.OnSearchChoseListener() {
            @Override
            public void onChose(int position) {
                choseOrder = mOrderList.get(position);
                getLoan(true);
            }

            @Override
            public void onShow() {
                setStatus(orderTv, orderImg, 4);
            }

            @Override
            public void onDismiss() {
                if (choseOrder != null) {
                    orderTv.setText(choseOrder.getTitle());
                    if (choseOrder.getItem().equals("-1")) {
                        setStatus(orderTv, orderImg, 1);
                    } else {
                        setStatus(orderTv, orderImg, 2);
                    }

                } else {
                    setStatus(orderTv, orderImg, 1);
                }

            }
        });
        orderSearchDialog.show();
    }

    private void initMoreDialog() {
        moreSearchDialog = new SearchMoreDialog(this, mMoreList, false, new SearchMoreDialog.OnSearchChoseListener() {
            @Override
            public void onConfirm() {
                getLoan(true);
            }

            @Override
            public void onShow() {
                setStatus(moreTv, moreImg, 4);
            }

            @Override
            public void onDismiss() {
                boolean hasCheck = false;
                for (int i = 0; i < mMoreList.size(); i++) {
                    for (int j = 0; j < mMoreList.get(i).getValue().size(); j++) {
                        if (mMoreList.get(i).getValue().get(j).isCheck()) {
                            hasCheck = true;
                            break;
                        }
                    }
                }
                if (hasCheck) {
                    setStatus(moreTv, moreImg, 2);
                } else {
                    setStatus(moreTv, moreImg, 1);
                }
            }
        });
        moreSearchDialog.show();
    }

    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.pledge_lay:
                if (pledgeSearchDialog == null) {
                    if (mPledgeList == null) {
                        getSearch("1", "2", "1");
                    } else {
                        initPledgeDialog();
                        pledgeSearchDialog.show();
                    }
                } else {
                    pledgeSearchDialog.show();
                }
                break;
            case R.id.order_lay:
                if (orderSearchDialog == null) {
                    if (mOrderList == null) {
                        getSearch("1", "2", "2");
                    } else {
                        initOrderDialog();
                    }
                } else {
                    orderSearchDialog.show();
                }
                break;
            case R.id.more_lay:
                if (moreSearchDialog == null) {
                    if (mMoreList == null) {
                        getSearch("1", "2", "3");
                    } else {
                        initMoreDialog();
                    }
                } else {
                    moreSearchDialog.show();
                }
                break;
            case R.id.left_back:
                this.finish();
                break;
        }
    }

    @Override
    public void onResponse(ResponseInfo responseInfo) {
        if (hasDestroy())
            return;
        super.onResponse(responseInfo);
        if (responseInfo.url.equals(Contant.LOAN_SEARCH)) {
            findViewById(R.id.search_lay).setVisibility(View.VISIBLE);
            if (responseInfo.isRequestOk) {
                try {
                    searchBean = JSON.parseObject(responseInfo.content, CreditSearchBean.class);
                    if (searchBean != null && searchBean.getLoan_loan_item_list() != null) {
                        for (int i = 0; i < searchBean.getLoan_loan_item_list().size(); i++) {
                            if (searchBean.getLoan_loan_item_list().get(i).getSearch_type().equals("1")) {
                                mPledgeList = new ArrayList<>();
                                if (searchBean.getLoan_loan_item_list().get(i).getSearch_item() != null &&
                                        searchBean.getLoan_loan_item_list().get(i).getSearch_item().size() > 0)
                                    mPledgeList.addAll(searchBean.getLoan_loan_item_list().get(i).getSearch_item().get(0).getValue());
                                SearchValueBean value = new SearchValueBean();
                                if (chosePledge==null)
                                value.setCheck(true);
                                value.setTitle("不限抵押");
                                value.setItem("-1");
                                mPledgeList.add(0, value);

                            } else if (searchBean.getLoan_loan_item_list().get(i).getSearch_type().equals("2")) {
                                mOrderList = new ArrayList<>();
                                if (searchBean.getLoan_loan_item_list().get(i).getSearch_item() != null &&
                                        searchBean.getLoan_loan_item_list().get(i).getSearch_item().size() > 0)
                                    mOrderList.addAll(searchBean.getLoan_loan_item_list().get(i).getSearch_item().get(0).getValue());
                                SearchValueBean value = new SearchValueBean();
                                if (choseOrder==null)
                                value.setCheck(true);
                                value.setTitle("默认排序");
                                value.setItem("-1");
                                mOrderList.add(0, value);
                            } else if (searchBean.getLoan_loan_item_list().get(i).getSearch_type().equals("3")) {
                                mMoreList = new ArrayList<>();
                                if (searchBean.getLoan_loan_item_list().get(i).getSearch_item() != null &&
                                        searchBean.getLoan_loan_item_list().get(i).getSearch_item().size() > 0)
                                    mMoreList.addAll(searchBean.getLoan_loan_item_list().get(i).getSearch_item());
                            }
                        }
                        if (responseInfo.params.get("first_load").equals("2")) {
                            initSearchData();
                            getLoan(true);
                        }
                        if (responseInfo.params.get("need_show").equals("2")) {
                            if (responseInfo.params.get("type").equals("1")) {
                                initPledgeDialog();
                                pledgeSearchDialog.show();
                            } else if (responseInfo.params.get("type").equals("2")) {
                                initOrderDialog();
                                orderSearchDialog.show();
                            } else if (responseInfo.params.get("type").equals("3")) {
                                initMoreDialog();
                                moreSearchDialog.show();
                            }

                        }
                    }
                } catch (Exception e) {
                    Log.e("zwj", "e==" + e.toString());
                }

            }
        }else if (responseInfo.url.equals(Contant.LOAN_SEARCH_LIST)) {
            if (mPtrFrame.isRefreshing()) {
                mPtrFrame.refreshComplete();
            }

            if (responseInfo.isRequestOk) {
                try {
                    BankLoanSearchListBean bean = JSON.parseObject(responseInfo.content, BankLoanSearchListBean.class);
                    if (bean != null && bean.getLoan_search_list() != null) {
                        if (bean.getLoan_search_list().size() > 0)
                            page++;
                            loanList.addAll(bean.getLoan_search_list());
                        mAdapter.notifyDataSetChanged();

                    }
                    if (loanList.size() == 0) {
                        if (itemMap.size() == 0) {
                            loadView.noResult();
                        } else {
                            loadView.noResultWithRefresh();
                        }

                    } else {
                        loadView.finish();
                    }


                } catch (Exception e) {

                    if (page == 1) {
                        loadView.fail();
                    }

                }
            } else {
                if (page == 1) {
                    loadView.fail();
                }
            }
        }
    }
}
